#!/usr/bin/env python
#
# Copyright 2015 Time-My-Life team (NSC 2015).
#
import webapp2
import jinja2
import os
import numpy as np
import matplotlib.pyplot as plt
import logging
import StringIO
from dbase import *

os.environ["MATPLOTLIBDATA"] = os.getcwdu()  # own matplotlib data
os.environ["MPLCONFIGDIR"] = os.getcwdu()    # own matplotlibrc

class ViewHandler(webapp2.RequestHandler):
    def get(self):
        ''' Generate webpage for viewing status '''
        try:
            # 1. extract 'id' parameter as integer
            id = int(self.request.get('id'))
            # 2. query for corresponding Account
            account_query = Account.query(Account.id==id)
            accounts = account_query.fetch(1)
            # 3. check for additional parameters
            values = self.request.get('values')
            # 4. generate webpage
            if values=='':
                # 4.1 create template from 'view_ui.html'
                logging.info('Generate UI for viewing for %d'%id)
                template = JINJA_ENV.get_template('view_ui.html')
                # 4.2 prepare template_values
                template_values = {'id':id}
            else:
                # 4.3 create template from 'view_result.html'
                template = JINJA_ENV.get_template('view_ui.html')
                template_values = {}
                # 4.4 generate figures
                x = np.arange(0,24)
                val_lst = values.split(',')
                y = [float(v) for v in val_lst]
                plt.title('Usage')
                plt.xlabel('Hour')
                plt.ylabel('Minute')
                index = range(0,24)
                plt.xticks(index,x)
                plt.bar(x,y,color = 'red',align="center")
                rv = StringIO.StringIO()
                plt.savefig(rv, format="png")
                plt.clf()
                # 4.5 prepare template_values
                template_values = {'id':id,'img_src':rv.getvalue().encode("base64").strip()}
                logging.info('Generate UI for showing results for %d'%id)
        except:
            # 5. create template from 'view_error.html'
            template = JINJA_ENV.get_template('view_error.html')
            template_values = {}
            logging.debug('Wrong ID parameter')

        self.response.write(template.render(template_values))

    def post(self):
        ''' Query for conclusion based on view selection '''
        try:
            # 1. extract 'id' parameter as integer
            id = int(self.request.get('id'))
            # 2. query for corresponding Account

            account_query = Account.query(Account.id==id)
            accounts = account_query.fetch(1)
            if len(accounts) > 0:
            # 3. check for additional parameters
                params = self.request.get('view-choice')
                logging.info(params)
            # 4. query for corresponding DataObject
                if params == 'weekday':
                    dataobj_query = DataObject.query(ancestor=accounts[0].key).filter(DataObject.day_of_week.IN ([1,2,3,4,5]))
                if params == 'holiday':
                    dataobj_query = DataObject.query(ancestor=accounts[0].key).filter(DataObject.day_of_week.IN ([0,6]))
                if params == 'alldays':
                    dataobj_query = DataObject.query(ancestor=accounts[0].key).filter(DataObject.day_of_week.IN ([0,1,2,3,4,5,6]))
                if params == 'monday':
                    dataobj_query = DataObject.query(ancestor=accounts[0].key).filter(DataObject.day_of_week == 1)
                if params == 'tuesday':
                    dataobj_query = DataObject.query(ancestor=accounts[0].key).filter(DataObject.day_of_week == 2)
                if params == 'wednesday':
                    dataobj_query = DataObject.query(ancestor=accounts[0].key).filter(DataObject.day_of_week == 3)
                if params == 'thursday':
                    dataobj_query = DataObject.query(ancestor=accounts[0].key).filter(DataObject.day_of_week == 4)
                if params == 'friday':
                    dataobj_query = DataObject.query(ancestor=accounts[0].key).filter(DataObject.day_of_week == 5)
                if params == 'saturday':
                    dataobj_query = DataObject.query(ancestor=accounts[0].key).filter(DataObject.day_of_week == 6)
                if params == 'sunday':
                    dataobj_query = DataObject.query(ancestor=accounts[0].key).filter(DataObject.day_of_week == 0)
            # 5. calculate results with numpy
                dataobjs = dataobj_query.fetch()
                x = np.zeros(len(dataobjs[0].values))
                count = 0
                for obj in dataobjs:
                    arr = np.array(obj.values)
                    x = np.add(x,arr)
                    count = count+1
                z = x/count
                logging.debug(str(z))
                avg_lst = [str(v) for v in z]
                avg_txt = ','.join(avg_lst)
                logging.debug(avg_txt)
            # 6. generate response URL for /view?id=XXXX&params=YYYY
            resp_url = '/view?id=%d&values=%s'%(id,avg_txt)        
            logging.info('Generate conclusion for ID: %d'%id)
        except:
            # 7. generate response URL for /view
            resp_url = '/view?id=%d'%(id)
            
            logging.debug('Wrong ID parameter')
        self.redirect(resp_url)

JINJA_ENV = jinja2.Environment(

    loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),
    extensions=['jinja2.ext.autoescape'],
    autoescape=True)


app = webapp2.WSGIApplication([
    ('/view', ViewHandler)
], debug=True)